<template>
  <div v-show="showModal" class="my-modal">
    <div class="bg-masker" @click="closeModal" data-type='cancel'></div>
    <div class="my-content">
      <!-- <div @click="closeModal" class="c-pa c-p-t0 c-p-r0 c-ww60 c-hh60 c-flex-row c-flex-center">
        <i class="iconfont c-fs22 c-fc-gray">&#xe61b;</i>
      </div> -->
      <header class="c-pv32 c-fs28 c-fw-b c-textAlign-c">聊天室带货</header>
      <section class="c-contexty-scroll c-ph30 c-hh640 c-pb30">
        <div class="c-pv24 c-ph24 c-flex-row c-bg-white c-mb20 c-br8" v-for="(item,index) in recommendList" :key="index" @click="toggleChecked(index)">
          <!-- 测评 -->
          <div v-if="item.prodType == 11" class="c-ww180 c-hh120 c-flex-row c-flex-center c-bd1 c-text-hidden c-br10 c-p">
            <img :src="$addXossFilter((item.relationType == relationTypeMap.collage?item.cover:item.avatar), require('@/assets/examination_defult.png'))" class="c-h" alt="">
            <div class="c-br-tl10 c-br-br10 c-pa c-p-t0 c-p-l0 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{mapType[item.prodType]}}</div>
          </div>
          <!-- 活动 -->
          <div v-else-if="item.prodType == 7" class="c-ww180 c-hh120 c-flex-row c-flex-center c-bd1 c-text-hidden c-br10 c-p">
            <img :src="$addXossFilter((item.relationType == relationTypeMap.collage?item.cover:item.avatar), require('@/assets/activity_defult.png'))" class="c-w100" alt="">
            <div class="c-br-tl10 c-br-br10 c-pa c-p-t0 c-p-l0 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{mapType[item.prodType]}}</div>
          </div>
          <!-- 表单 -->
          <div v-else-if="item.prodType == 76" class="c-ww180 c-hh120 c-flex-row c-flex-center c-bd1 c-text-hidden c-br10 c-p">
            <img :src="$addXossFilter((item.relationType == relationTypeMap.collage?item.cover:item.avatar), require('@/assets/form_defult.png'))" class="c-w100" alt="">
            <div class="c-br-tl10 c-br-br10 c-pa c-p-t0 c-p-l0 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{mapType[item.prodType]}}</div>
          </div>
          <!-- 资料 -->
          <div v-else-if="item.prodType == 8" class="c-ww180 c-hh120 c-flex-row c-flex-center c-bd1 c-text-hidden c-br10 c-p">
            <img :src="$addXossFilter((item.relationType == relationTypeMap.collage?item.cover:item.avatar), require('@/assets/datum_defult.png'))" class="c-w100" alt="">
            <div class="c-br-tl10 c-br-br10 c-pa c-p-t0 c-p-l0 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{mapType[item.prodType]}}</div>
          </div>
          <!-- vip -->
          <div v-else-if="item.prodType == 1 ||item.prodType == 31" class="c-ww180 c-hh120 c-text-hidden c-br10 c-p">
            <vip-custom-img :cover="item.vipInfo.cover" :imgClass="'c-h'" :hasText="false" v-if="item.vipInfo && item.vipInfo.cover" />
            <img v-else :src="require('@/assets/i/wap/course/vip.png')" class="c-w100 c-h" alt="">
            <div class="c-br-tl10 c-br-br10 c-pa c-p-t0 c-p-l0 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{mapType[item.prodType]}}</div>
          </div>
          <!-- svip -->
          <div v-else-if="item.prodType == 23||item.prodType == 32" class="c-ww180 c-hh120 c-text-hidden c-br10 c-p">
            <vip-custom-img :cover="item.vipInfo.cover" :imgClass="'c-h'" :hasText="false" v-if="item.vipInfo && item.vipInfo.cover" />
            <img v-else :src="require('@/assets/i/wap/course/svip.png')" class="c-w100 c-h" alt="">
            <div class="c-br-tl10 c-br-br10 c-pa c-p-t0 c-p-l0 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{mapType[item.prodType]}}</div>
          </div>
          <!-- 优惠券 -->
          <div v-else-if="item.prodType == 92" class="c-text-hidden c-p c-flex-row c-flex-grow1">
            <div :class="(item.status>=3||timeChat(item.endTime))?'exchange-couponGray':item.type == 1 ? 'exchange-left' : 'coupon-left'" class="c-ww120 c-hh120 c-flex-shrink0 c-flex-column  c-aligni-center c-justify-center">
              <div v-if="item.type == 1" class="c-fs32 c-fc-white c-textAlign-c">兑换券</div>
              <div v-else-if="item.type == 4" class="c-fs32 c-fc-white c-textAlign-c">抵价券</div>
              <section v-else>
                <div v-if="item.type == 5" class="c-fs40 c-fc-white c-textAlign-c c-text-ellipsis1 c-hh60 c-lh60">{{item.price * 1}}<span class="c-fs20">折</span></div>
                <div v-else class="c-fs40 c-fc-white c-textAlign-c c-text-ellipsis1 c-hh60 c-lh60"><span class="c-fs20">{{'￥' | iosPriceFilter('Live')}}</span>{{item.price.split('.')[0]}}</div>
                <div class="c-fs20 c-fc-white c-textAlign-c c-text-ellipsis1 c-hh60 c-lh60">{{Number(item.amount) > 0 ? ('满' + item.amount.split('.')[0] + '元可用') : '无门槛'}}</div>
              </section>
            </div>
            <div class="c-bg-white c-flex-grow1 c-text-hidden c-flex-column c-justify-sb">
              <div class="c-fs24 c-fc-xblack c-text-ellipsis1 c-ph20">{{item.name}}</div>
              <div class="c-flex-column  c-justify-sb c-pl20  c-fs20 c-fc-gray">
                <div v-if="item.validStatus == 1">领券当日起{{item.validPeriod}}天内可用</div>
                <div v-else-if="item.validStatus == 2">领券次日起{{item.validPeriod}}天内可用</div>
                <div v-else class="c-text-ellipsis1">{{item.startTime.replace(/-/g,'.').split(' ')[0]}} - {{item.endTime.replace(/-/g,'.').split(' ')[0]}}</div>
                <div class="c-flex-row c-aligni-end">
                  <div class="c-fs20 c-flex-grow1 c-fc-gray c-text-ellipsis1">{{item | couponApplyText}}</div>
                  <div v-if="!(item.status>=3||timeChat(item.endTime))">
                    <div v-if='item.limit!=0&&item.leftNum<=0' class="c-ww80 c-hh36 c-flex-row c-flex-center c-br20 c-fs20 c-fc-white c-bg-ccc">已秒光</div>
                    <div v-else v-show="!updateStatus" class="c-ww80 c-hh36 c-flex-row c-flex-center c-br20 c-fs20 c-fc-white c-bg-xblue" @click.stop="clickSentRecommend(item)">发送</div>
                  </div>
                  <div v-else class="icon iconfont c-fs80 c-fc-sgray c-pa c-p-r0">&#xe850;</div>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="c-ww180 c-hh120 c-text-hidden c-flex-row c-flex-center c-bd1 c-br10 c-p">
            <img :src="$addXossFilter((item.relationType == relationTypeMap.collage?item.cover:item.avatar), require('@/assets/defult270.png'))" class="c-w100" alt="">
            <div class="c-pa c-p-t0 c-p-l0 c-br-tl10 c-br-br10 c-flex-row c-flex-center c-translucent-balck60 c-fc-white c-fs16 c-ph8 c-hh24">{{item.prodType == 5 ? courseTypeMap[item.courseType]:mapType[item.prodType]}}</div>
          </div>
          <div v-if="item.prodType != 92" class="c-pl20 c-fs24 c-hh120 c-flex-grow1 c-w0 c-flex-column c-justify-sb">
            <div :class="item.prodType == 7 && item.relationType==relationTypeMap.flashSales && item.atName ? 'c-text-ellipsis2':'c-text-ellipsis1'">
              <span class="bg-flashSales" v-if="item.relationType==relationTypeMap.flashSales || item.relationType==relationTypeMap.collage">{{item.relationType==relationTypeMap.flashSales?(Number(item.price) == 0 ? '限时免费' : '限时折扣'):'拼团'}}</span>{{item.name}}
            </div>
            <div v-if="item.prodType == 7 && item.relationType==relationTypeMap.flashSales && item.atName" class="c-fs20 c-text-ellipsis1 c-fc-sblack">{{item.atName}}</div>
            <div class="c-flex-row c-aligni-end">
              <span v-if="(item.relationId&&item.relationType)&&(item.relationId!=0 || item.relationType!=0 )" class="c-fc-xlred c-flex-grow1 c-w0"><span class="c-fc-gray c-fs18 text-decoration c-mr8">{{'￥' | iosPriceFilter('Live')}}{{item.subContent?item.subContent:item.prodPrice}}</span><span class="c-fc-gray c-fs18 c-mr8">{{item.relationType==relationTypeMap.flashSales?'折后价':item.relationType==relationTypeMap.collage?'团长价':''}}</span><span>{{'￥' | iosPriceFilter('Live')}}{{item.relationType==relationTypeMap.collage?item.playersPrice:item.price}}</span></span>
              <span v-else :class="item.prodType == 76 ?'vis-hidden-important':''" class="c-fc-xlred c-flex-grow1 c-w0"><span v-if="item.payType == 2 || item.payType == 4">{{'￥' | iosPriceFilter('Live')}}</span>{{item.payType == 2 || item.payType == 4 ? item.prodPrice : item.payType == 3 ? '加密' : (item.payType==5 ? '购买指定课程参与':(item.payType==6 ? '指定人员购买':'免费'))}}</span>
              <div v-if='item.limit!=0&&item.leftNum<=0' class="c-ww80 c-hh36 c-flex-row c-flex-center c-br20 c-fs20 c-fc-white c-bg-xblue">已秒光</div>
              <div v-else v-show="!updateStatus" class="c-ww80 c-hh36 c-flex-row c-flex-center c-br20 c-fs20 c-fc-white c-bg-xblue" @click.stop="clickSentRecommend(item)">发送</div>
            </div>
          </div>
          <div v-if="detailId && updateStatus == 'ADD'" class="c-flex-row c-flex-center c-pl20">
            <i v-if="item.isChecked" class="iconfont c-fs34 c-fc-xblue">&#xe6eb;</i>
            <i v-else class="iconfont c-fs34 c-fc-e6">&#xe692;</i>
          </div>
        </div>
        <loading-status-tem :noData="recommendList.length == 0" :noDataText="'暂无好货'"></loading-status-tem>
      </section>
      <footer class="person-footer" v-if="detailId">
        <template v-if="!updateStatus">
          <!-- <div @click="clickRemove" class="c-ww270 c-hh60 c-br30 c-flex-row c-flex-center c-bg-e6">移除</div> -->
          <div @click="clickAdd" class="c-w100 c-hh60 c-br30 c-flex-row c-flex-center c-bg-xblue c-fc-white">添加</div>
        </template>
        <template v-if="updateStatus == 'ADD'">
          <div class="c-fs24">已选<span class="c-fc-xblue c-ph10">{{commerceChooseNum}}</span>件</div>
          <div @click="clickConfirmAdd" class="c-ww270 c-hh60 c-br30 c-flex-row c-flex-center c-bg-xblue c-fc-white">确认添加</div>
        </template>
        <!-- <template v-if="updateStatus == 'DEL'">
          <div class="c-fs24">当前已选<span class="c-fc-xblue c-ph10">{{removeProdIdList.length}}</span>件</div>
          <div @click="clickConfirmRemove" v-show="removeProdIdList.length" class="c-ww270 c-hh60 c-br30 c-flex-row c-flex-center c-bg-xxlred c-fc-white">确认移除</div>
        </template> -->

      </footer>
    </div>

  </div>
</template>

<script>
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import VipCustomImg from "@/components/templates/common/VipCustomImg.vue";
import { utilJs } from "@/utils/common.js";
export default {
  components: {
    loadingStatusTem,
    VipCustomImg,
  },
  inject: ['goRecommendBuy'],
  props: {
    socialRoomId: {
      type: String,
      default: ''
    },
    showModal: {
      type: Boolean,
      default: false
    },
    liveId:{
      type: Number,
      default:0 //独立直播间的lpId
    },
    detailId:{
       type: Number,
      default:0 //独立直播间的场次id
    }
  },
  data() {
    return {
      recommendList: [],
      mapType: global.prodMapType,
      relationTypeMap: global.relationTypeMap,
      courseTypeMap: global.prodCourseType,
      updateStatus:'',
      commerceChooseNum:0,
    };
  },
  watch: {
    showModal(val) {
      if (val) {
        this.updateStatus = '';
        if (this.detailId) {
          this.getPersonalRecommendList();
        } else {
           this.getRecommendList();
        }
      }
    },
    recommendList(val) {
      let count = 0;
      val.forEach((item) => {
        if (item.isChecked) {
          count++;
        }
      })
      this.commerceChooseNum = count;
    },
  },
  methods: {
    toggleChecked(index) {
      //独立直播间 && 添加带货操作 && 不是已添加的带货
      console.log(this.detailId, this.updateStatus)
       let item = this.recommendList[index];
       if (this.detailId && this.updateStatus == 'ADD') {
        let checked = !item.isChecked;
        if (this.commerceChooseNum >= 20 && checked) {
           this.$showCjToast({
            text: "最多只能添加20个商品",
            type: "warn",
          });
          return;
        }
        this.recommendList[index].isChecked = !item.isChecked
        this.recommendList = [...this.recommendList];
       }

      // if (this.detailId && this.updateStatus == 'ADD' && !this.oldRecommendList.includes(`${item.prodId}_${item.prodType}`)) {
      //    if (this.addProdIdList.includes(item.lgId)) {
      //     this.addProdIdList = this.addProdIdList.filter(i => i != item.lgId);
      //     return;
      //   }
      //   if (this.oldRecommendList.length + this.addProdIdList.length == 20) {
      //     this.$showCjToast({
      //       text: "最多只能添加20个商品",
      //       type: "warn",
      //     });
      //     return;
      //   }
      //   this.addProdIdList.push(item.lgId)
      //   return;
      // }
      //独立直播间 && 添加带货操作 && 不是已添加的带货
      // if (this.detailId && this.updateStatus == 'DEL') {
      //   if (this.removeProdIdList.includes(item.srgId)) {
      //     this.removeProdIdList = this.removeProdIdList.filter(i => i != item.srgId);
      //   } else {
      //     this.removeProdIdList.push(item.srgId)
      //   }
      //   return;
      // }
      if (this.detailId && this.updateStatus) {
        return;
      }
      if (this.goRecommendBuy) {
        //依赖注入存在(优惠卷不跳转)
        if (item.prodType == 92) return;
        item.isShowDesc = true;
        item.subProdType = item.prodType;
        item.subMsgId = item.id;
        item.voiceStatus = item.courseType;
        item.subProdId = item.subId || null;
        this.goRecommendBuy(item);
      } else {
         this.$emit('goDetail', item);
      }

    },
    getRecommendList() {
      let getUrl = `${global.apiurl}social/getSocialRoomGoods/${this.socialRoomId}`
      utilJs.getMethod(getUrl, res => {
        this.recommendList = res.socialGoods || [];
      })
    },
    //获取独立直播间已选的带货
    getPersonalRecommendList() {
      this.updateStatus = '';
      utilJs.getMethod(`${global.apiurl}appletLivePersonal/getSocialRoomGoods/${this.liveId}?detailId=${this.detailId}`, res => {
        console.log(res);
        this.recommendList = res || [];
        let ids = [];
        res.forEach((item) => {
          ids.push([item.prodId, item.prodType, item.relationId, item.relationType, item.subProdId].join("_"))
        })
        this._hadAddPersonalRecommendIds = ids;
        console.log("xxxx", this._hadAddPersonalRecommendIds)
      })
    },
    //独立直播间带货奖池
    getProductInfo() {
      utilJs.getMethod(`${global.apiurl}appletLivePersonal/getGoodsPool/${this.liveId}`, res => {
        if (this.updateStatus == 'ADD') {
          //添加的时候
          res.forEach((item) => {
            if (this._hadAddPersonalRecommendIds.includes([item.prodId, item.prodType, item.relationId, item.relationType, item.subProdId].join("_"))) {
              item.isChecked = true;
            }
          })
        }
        this.recommendList = res || [];
        console.log("recommendList", this.recommendList)
      });
    },
    clickRemove() {
       this.updateStatus = 'DEL';
       this.removeProdIdList = [];
    },
    clickAdd() {
      this.updateStatus = 'ADD';
      this.getProductInfo();
    },
    clickConfirmAdd() {
      this.addGoods();
    },
    addGoods() {
      let data = {
        detailId: this.detailId,
        lgIds:[]
      };
      this.recommendList.forEach((item) => {
        if (item.isChecked) {
          data.lgIds.push(item.lgId)
        }
      })
      let url = `${global.apiurl}appletLivePersonal/addSocialRoomGoods/${this.liveId}`;
      utilJs.postMethod(url, data, () => {
        this.$showCjToast({
          text: "添加成功",
          time: 3000,
        });
        this.getPersonalRecommendList();
      });
    },
    removeGoods() {
      let url = `${global.apiurl}appletLivePersonal/delSocialRoomGoods/${this.liveId}`;
      let data = {
        srgIds: this.removeProdIdList
      };
      utilJs.postMethod(url, data, () => {
        this.$showCjToast({
          text: "移除成功",
          time: 3000,
        });
        this.getPersonalRecommendList();
      });
    },
    timeChat(timeType) {
      let nowtime = new Date().getTime();
      let couponTime = new Date(timeType.replace(/-/g, '/')).getTime();
      if (nowtime >= couponTime) {
        return true
      } else {
        return false
      }
    },
    clickSentRecommend(item) {
      if (item.relationType == this.relationTypeMap.flashSales) {
        if (item.isFlashProd == -1 || item.status == -1 || this.timeChat(item.endTime)) {
          this.$showCjToast({
            text: item.isFlashProd == -1 ? '该商品未参加限时购' : "活动已结束",
            type: "warn",
            time: 1500
          });
          return
        }
        if (!this.timeChat(item.startTime)) {
          this.$showCjToast({
            text: "活动未开始",
            type: "warn",
            time: 1500
          });
          return
        }
      }
      if (item.relationType == this.relationTypeMap.collage || item.relationType == this.relationTypeMap.coupon) {
        if (item.status >= 3 || this.timeChat(item.endTime)) {
          this.$showCjToast({
            text: "活动已结束",
            type: "warn",
            time: 1500
          });
          return
        }
        if (item.relationType == this.relationTypeMap.coupon && item.leftNum <= 0) {
          this.$showCjToast({
            text: "没有剩余产品",
            type: "warn",
            time: 1500
          });
          return
        }
      }
      this.$emit("clickSentRecommend", item);
    },
    closeModal(e) {
      if (this.detailId && this.updateStatus == 'DEL') {
        this.updateStatus = '';
        return;
      }
      if (this.detailId && this.updateStatus == 'ADD') {
        this.getPersonalRecommendList();
        return;
      }
      this.$emit("closeRecommendModal");
    }
  },
  activated() {
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.my-modal {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1002;
  width: 100%;
  height: 100%;
  padding-top: 3rem;
}

.bg-masker {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  overflow: hidden;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
}

.my-content {
  position: absolute;
  bottom: 0;
  z-index: 1;
  width: 100%;
  border-radius: 0.75rem 0.75rem 0 0;
  background-color: #F5F7FA;
}
.text-decoration {
  text-decoration: line-through;
}
.coupon-left {
  background: url("../../../../public/i/wap/coupon/di.png") no-repeat 100%;
  background-size: 100% 100%;
}
.exchange-left {
  background: url("../../../../public/i/wap/coupon/exchangenew.png") no-repeat 100%;
  background-size: 100% 100%;
}
.exchange-couponGray {
  background: url("../../../../public/i/wap/coupon/coupon_gray.png") no-repeat 100%;
  background-size: 100% 100%;
}
.all-coupon-bg {
  background-color: #f4f7f9;
}
.bg-flashSales{
  display: inline-block;
  font-size: 0.4rem;
  padding: 0 0.25rem;
  margin-right: 0.25rem;
  color: #fff;
  background: linear-gradient(to right,rgba(255,83,85,1.0) 0%, rgba(255,83,85,0.7) 100%);
  border-radius: 0.35rem 0 0.35rem 0;
}
.person-footer{
  width: 100%;
  height: 2.5rem;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #ededed;
  padding: 0 0.5rem;
  color: #333;
  font-size: 0.6rem;
}
</style>
